package com.qf.account;


import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author wangyu  业务逻辑
 * @Classname: AccountServiceinpl
 * @Description: TEST
 * @date 2022-04-06 17:04
 */
public class AccountServiceinpl implements AccountService{
    //    1收集参数
    public void transfer(String fromNo, String pwd, String toNo, double money) {
//        AccountDao accountDaoimpl = new AccountDaoimpl2();
        AccountDao accountDaoimpl = new AccountDaoimpl();
//    2 组织完善业务功能
//        2.1 验证fromNo是否存在
        try {
//            调用 DBUtils 开启事务
            DBUtils.begin();
            Account account = accountDaoimpl.select(fromNo);
            if (account == null) {
                throw new RuntimeException("卡号不存在！");
            }
//        2.2 验证fromNd 密码是否正确
            if (!account.getPassword().equals(pwd)) {
                throw new RuntimeException("密码错误！");
            }
//        2.3验证余额是否充足
            if (account.getBalance() < money) {
                throw new RuntimeException("余额不足！");
            }
//        2.4 验证fromNd是否存在
            Account account1 = accountDaoimpl.select(toNo);
            if (account1 == null) {
                throw new RuntimeException("对方卡号不存在！");
            }
//        2.5减少 fromNo的余额
            account.setBalance(account.getBalance() - money);
            accountDaoimpl.update(account);
//        2.6增加toNo余额
            account1.setBalance(account1.getBalance() + money);
            accountDaoimpl.update(account1);
            System.out.println("转账成功！");
//            转账成功，整个事务提交
            DBUtils.commit();
        } catch (RuntimeException e) {
            System.out.println("转账失败！");
            //            如果当前事务出现异常，则回滚当前事务
            DBUtils.rollback();
            e.printStackTrace();
        }
    }
}
